package com.simdo.g768.Dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.loper7.date_time_picker.dialog.CardDatePickerDialog;
import com.simdo.g768.Adapter.MqttInfoAdapter;
import com.simdo.g768.MainActivity;
import com.simdo.g768.Mqtt.MqttBean;
import com.simdo.g768.Mqtt.MqttManage;
import com.simdo.g768.Mqtt.MqttMsg;
import com.simdo.g768.R;
import com.simdo.g768.Util.DateUtil;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MqttInfoDialog extends Dialog {

    private final Context mContext;

    public MqttInfoDialog(Context context) {
        super(context, R.style.Theme_B97621);
        this.mContext = context;

        View view = View.inflate(context, R.layout.dialog_mqtt_info, null);
        this.setContentView(view);
        this.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        //this.setCancelable(false);   // 返回键不消失
        //设置dialog大小，这里是一个小赠送，模块好的控件大小设置
        Window window = this.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.setNavigationBarColor(Color.parseColor("#2A72FF"));
        //window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        //StatusBarUtil.setLightStatusBar(window, true);
        WindowManager.LayoutParams lp = window.getAttributes();

        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);

        initView(view);
    }

    MqttInfoAdapter adapter;
    private void initView(View root) {
        root.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        TextView tv_start_time = root.findViewById(R.id.tv_start_time);
        TextView tv_end_time = root.findViewById(R.id.tv_end_time);
        // 获取当前时间
        Calendar currentCalendar = Calendar.getInstance();

        // 将当前时间格式化为可读的日期和时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate2 = sdf.format(currentCalendar.getTime());
        //设置默认时间
        tv_end_time.setText(formattedDate2);    //当前时间
        // 将时间设置为当天的0点0分0秒
        currentCalendar.set(Calendar.HOUR_OF_DAY, 0);
        currentCalendar.set(Calendar.MINUTE, 0);
        currentCalendar.set(Calendar.SECOND, 0);
        currentCalendar.set(Calendar.MILLISECOND, 0);
        //设置默认时间
        String formattedDate1 = sdf.format(currentCalendar.getTime());
        tv_start_time.setText(formattedDate1); //数据库中取

        tv_start_time.setOnClickListener(v -> {
            clickOperatorTime(tv_start_time, tv_end_time, true);
        });
        tv_end_time.setOnClickListener(v -> {
            clickOperatorTime(tv_end_time, tv_start_time, false);
        });

        TextView tv_mqtt_connect_state = root.findViewById(R.id.tv_mqtt_connect_state);
        tv_mqtt_connect_state.setText(MqttManage.build().notConnected() ? mContext.getString(R.string.connecting) : mContext.getString(R.string.connected));
        tv_mqtt_connect_state.setTextColor(MqttManage.build().notConnected() ? mContext.getColor(R.color.color_e65c5c) : mContext.getColor(R.color.green));

        root.findViewById(R.id.iv_mqtt_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MqttDialog dialog = new MqttDialog(mContext);
                dialog.show();
            }
        });

        RecyclerView rv_mqtt_info = root.findViewById(R.id.rv_mqtt_info);
        rv_mqtt_info.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new MqttInfoAdapter(mContext);
        rv_mqtt_info.setAdapter(adapter);
        adapter.setTime(DateUtil.dateToLong(formattedDate1, "yyyy-MM-dd HH:mm:ss"), DateUtil.dateToLong(formattedDate2, "yyyy-MM-dd HH:mm:ss"));
        adapter.updateDataList(MainActivity.getInstance().mqttList);

        MqttBean mqttBean = MainActivity.getInstance().mqttConnection.getMqttBean();

        CheckBox cb_is_show = root.findViewById(R.id.cb_is_show);
        cb_is_show.setChecked(mqttBean.isShow());
        cb_is_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().mqttConnection.getMqttBean().setShow(cb_is_show.isChecked());
            }
        });
    }

    private void clickOperatorTime(TextView textView, TextView textView2, boolean isStartTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 创建一个日历对象，用于设置默认时间
        Calendar defaultCalendar = Calendar.getInstance();

        // 创建一个日历对象，用于设置最小时间
        Calendar minCalendar = Calendar.getInstance();
        minCalendar.set(2023, Calendar.JANUARY, 1, 0, 0, 0); // 设置最小时间为 2023年1月1日 00:00

        CardDatePickerDialog cardDatePickerDialog = new CardDatePickerDialog.Builder(mContext)
                .setBackGroundModel(CardDatePickerDialog.CARD)
                .setDefaultTime(defaultCalendar.getTimeInMillis())  //从外面第二个取
                .setMaxTime(defaultCalendar.getTimeInMillis())  //从外面第二个取
                .setMinTime(minCalendar.getTimeInMillis())  //从外面第一个取
                .setWrapSelectorWheel(false)
                .showBackNow(false)
                .setOnChoose(mContext.getString(R.string.sure), millisecond -> {
                    // 创建 Date 对象并设置毫秒数
                    Date date = new Date(millisecond);
                    // 格式化日期
                    String formattedDate = sdf.format(date);
                    // 输出格式化后的日期
                    textView.setText(formattedDate);
                    long date1 = millisecond;
                    long date2 = DateUtil.dateToLong(textView2.getText().toString(), "yyyy-MM-dd HH:mm:ss");

                    if (!isStartTime){
                        millisecond = date2;
                        date2 = date1;
                        date1 = millisecond;
                    }

                    if (date1 > date2) {
                        MainActivity.getInstance().showToast(mContext.getString(R.string.start_min_end_time));
                        return null;
                    }
                    adapter.setTime(date1, date2);
                    adapter.updateDataList(MainActivity.getInstance().mqttList);
                    return null;
                })
                .setOnCancel(mContext.getString(R.string.close), () -> null).build();
        cardDatePickerDialog.setTitle(isStartTime ? mContext.getString(R.string.start_time) : mContext.getString(R.string.end_time));
        cardDatePickerDialog.show();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void notifyDataSetChanged(MqttMsg mqttMsg){
        if (mqttMsg == null) adapter.updateDataList(MainActivity.getInstance().mqttList);
        else adapter.addData(mqttMsg);
    }
}
